package com.itheima.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public StuOption stuCount() {
        List<Map> mapList = studentMapper.stuCount();
        List<String> nameList = new ArrayList<>();
        List<Object> numList = new ArrayList<>();
        for (Map map : mapList) {
            nameList.add((String) map.get("name"));
            numList.add(map.get("nums"));
        }
        StuOption stuOption = new StuOption();
        stuOption.setClazzList(nameList);
        stuOption.setDataList(numList);
        return stuOption;
    }

    @Override
    public List<Map> stuDegreeCount() {
        List<Map> stuList = studentMapper.stuDegreeCount();
        return stuList;
    }

    @Override
    public PageResult<Student> pageStu(StuQueryParam queryParam) {
        Page<Student> page = new Page<>(queryParam.getPage(), queryParam.getPageSize());
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(queryParam.getName()), Student::getName, queryParam.getName());
        queryWrapper.eq(queryParam.getDegree() != null, Student::getDegree, queryParam.getDegree());
        queryWrapper.eq(queryParam.getClazzId() != null, Student::getClazzId, queryParam.getClazzId());
        queryWrapper.eq(StrUtil.isNotBlank(queryParam.getClassName()), Student::getClazzName, queryParam.getClassName());
        page = page(page, queryWrapper);
        List<Student> students = page.getRecords();
        if (students.size() > 0) {
            students.forEach((student) -> {
                if (student != null){
                    Integer id = student.getClazzId();
                    Clazz clazz = clazzMapper.selectById(id);
                    if (clazz!=null){
                        student.setClazzName(clazz.getName());
                    }
                }
            });
        }
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

}
